package edu.itla.medifacil.persistence.managers;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import edu.itla.medifacil.persistence.entities.DoctorAssistant;
import edu.itla.medifacil.persistence.entities.People;
import edu.itla.medifacil.persistence.enums.Role;

public class AssistentManager {
	private EntityManager em = null;
	
	public AssistentManager() {
		this.em = Persistence.createEntityManagerFactory("MediFacil").createEntityManager();
	}
	

	public People save( Map<String, String> parameters ){
		PersonManager personManager = new PersonManager();
		People assistent = personManager.save(parameters, Role.ASSISTANT.getId());
		
		em.getTransaction().begin();
		
		em.createQuery( "DELETE FROM DoctorAssistant WHERE assistant_id =" + assistent.getId() ).executeUpdate();
		
		for( String key : parameters.keySet() ){
			if( key.startsWith("doctors") ){
				int doctorId = Integer.parseInt( parameters.get(key) );
				DoctorAssistant doctorAssistent = new DoctorAssistant();
				People doctor = personManager.find( doctorId );
				doctorAssistent.setAssistent( assistent );
				doctorAssistent.setDoctor( doctor );
				em.persist( doctorAssistent );
			}
		}
		
		em.getTransaction().commit();
		
		return this.find( assistent.getId() ); 
	}
	
	
	public void delete( int assistentId ){
		PersonManager patientManager = new PersonManager();
		patientManager.delete(assistentId);
	}

	public People find( int assistentId ){
		em.clear();
		return em.find( People.class, assistentId);
	}
	
	@SuppressWarnings("unchecked")
	public List<People> findAll(){
		return (List<People>) em.createQuery( "SELECT p FROM People p WHERE p.user.role.id =" + edu.itla.medifacil.persistence.enums.Role.ASSISTANT.getId() ).getResultList();
	}
}
